﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Web;
using System.Text.RegularExpressions;
#region Version Info
/* ========================================================================
* 【本页面功能概述】
*
* 作者：wangjianfeng 创建时间：2012/5/24 14:56:37
* 文件名：StringExtention.cs
*
* 修改者： 时间：
* 修改说明：
* ========================================================================
*/
#endregion
namespace Utils.Extention
{
    /// <summary>
    /// 字符串的扩展方法
    /// </summary>
    public static class StringExtention
    {
        /// <summary>
        /// DES加密密钥
        /// </summary>
        private const string ENCRYPTKEY = "W#B@l&og";

        #region DES方式加密字符串的方法
        /// <summary>
        /// DES方式加密字符串的方法
        /// </summary>
        /// <param name="s">要进行加密的字符串</param>
        /// <returns>加密后的字符串</returns>
        public static string DesEncrypt(this string s)
        {
            byte[] byKey = null;
            byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
            byKey = Encoding.Default.GetBytes(ENCRYPTKEY.Substring(0, 8));
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.Default.GetBytes(s);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Convert.ToBase64String(ms.ToArray());
        }

        /// <summary>
        /// DES方式加密字符串的方法
        /// </summary>
        /// <param name="s">要进行加密的字符串</param>
        /// <param name="key">密钥Key</param>
        /// <returns>加密后的字符串</returns>
        public static string DesEncrypt(this string s,string key)
        {
            byte[] byKey = null;
            byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
            byKey = Encoding.Default.GetBytes(key.Substring(0, 8));
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.Default.GetBytes(s);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Convert.ToBase64String(ms.ToArray());
        }
        #endregion

        #region DES方式解密字符串的方法
        /// <summary>
        /// DES方式解密字符串的方法
        /// </summary>
        /// <param name="s">要进行解密的字符串</param>
        /// <returns>解密后的字符串</returns>
        public static string DesDecrypt(this string s)
        {
            byte[] byKey = null;
            byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
            byte[] inputByteArray = new Byte[s.Length];
            byKey = Encoding.Default.GetBytes(ENCRYPTKEY.Substring(0, 8));
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            inputByteArray = Convert.FromBase64String(s);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Encoding.Default.GetString(ms.ToArray());
        }

        /// <summary>
        /// DES方式解密字符串的方法
        /// </summary>
        /// <param name="s">要进行解密的字符串</param>
        /// <param name="key">要解密的密钥</param>
        /// <returns>解密后的字符串</returns>
        public static string DesDecrypt(this string s,string key)
        {
            byte[] byKey = null;
            byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
            byte[] inputByteArray = new Byte[s.Length];
            byKey = Encoding.Default.GetBytes(key.Substring(0, 8));
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            inputByteArray = Convert.FromBase64String(s);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Encoding.Default.GetString(ms.ToArray());
        }
        #endregion

        /// <summary>
        /// 扩展方法将字符串转md5
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string MD5Encrypt(this string s)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] bytes = md5.ComputeHash(Encoding.Default.GetBytes(s));
            string result = string.Empty;
            foreach (byte b in bytes)
            {
                result += b.ToString("x");
            }
            return result;
        }



        /// <summary>
        /// 扩展方法，将字符串转成base64
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string ToBase64(this string s)
        {
            byte[] b = System.Text.Encoding.Default.GetBytes(s);
            //转成 Base64 形式的 System.String
            return Convert.ToBase64String(b);
        }

        /// <summary>
        /// 将base64字串转成字符串
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string FromBase64(this string s)
        {
            byte[] c = Convert.FromBase64String(s);
            return System.Text.Encoding.Default.GetString(c);
        }

        /// <summary>
        /// base64在url中传递时处理+/
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string ToBase64Url(this string s)
        {
            return s.Replace("+", "-").Replace("/", "*");
        }

        /// <summary>
        /// 将base64中的+/还原回来
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string FromBase64Url(this string s)
        {
            return s.Replace("-", "+").Replace("*", "/");
        }

        /// <summary>
        /// 过滤字符串中注入SQL脚本的方法
        /// </summary>
        /// <param name="source">传入的字符串</param>
        /// <returns>过滤后的字符串</returns>
        public static string SqlFilter(this string source)
        {
            //半角括号替换为全角括号
            source = source.Trim().Replace("'", "''").Replace(";", "；").Replace("(", "（").Replace(")", "）");

            //去除执行SQL语句的命令关键字
            source = Regex.Replace(source, "select", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "insert", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "update", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "delete", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "drop", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "truncate", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "declare", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "xp_cmdshell", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "/add", "", RegexOptions.IgnoreCase);
            //Regex.Replace(source, "asc(", "", RegexOptions.IgnoreCase);
            //Regex.Replace(source, "mid(", "", RegexOptions.IgnoreCase);
            //Regex.Replace(source, "char(", "", RegexOptions.IgnoreCase);
            //Regex.Replace(source, "count(", "", RegexOptions.IgnoreCase);
            //fetch 
            //IS_SRVROLEMEMBER
            //Cast(

            source = Regex.Replace(source, "net user", "", RegexOptions.IgnoreCase);

            //去除执行存储过程的命令关键字 
            source = Regex.Replace(source, "exec", "", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "execute", "", RegexOptions.IgnoreCase);

            //去除系统存储过程或扩展存储过程关键字
            source = Regex.Replace(source, "xp_", "x p_", RegexOptions.IgnoreCase);
            source = Regex.Replace(source, "sp_", "s p_", RegexOptions.IgnoreCase);

            //防止16进制注入
            source = Regex.Replace(source, "0x", "0 x", RegexOptions.IgnoreCase);

            return source;
        }

        /// <summary>
        /// 过滤字符串中的注入跨站脚本(先进行UrlDecode再过滤脚本关键字),段少飞
        /// 过滤脚本如:<script>window.alert("test");</script>输出window.alert("test");
        /// 如<a href = "javascript:onclick='fun1();'">输出<a href=" onXXX='fun1();'">
        /// 过滤掉javascript和 onXXX
        /// </summary>
        /// <param name="source">需要过滤的字符串</param>
        /// <returns>过滤后的字符串</returns>
        public static string XSSFilter(this string source)
        {
            if (source == "") return source;
            string result = HttpUtility.UrlDecode(source.Trim());

            string replaceEventStr = " onXXX =";
            string tmpStr = "";

            string patternGeneral = @"<[^<>]*>";                              //例如 <abcd>
            string patternEvent = @"([\s]|[:])+[o]{1}[n]{1}\w*\s*={1}";     // 空白字符或: on事件=
            string patternScriptBegin = @"\s*((javascript)|(vbscript))\s*[:]?";  // javascript或vbscript:
            string patternScriptEnd = @"<([\s/])*script.*>";                       // </script>   
            string patternTag = @"<([\s/])*\S.+>";                       // 例如</textarea>

            Regex regexGeneral = new Regex(patternGeneral, RegexOptions.IgnoreCase | RegexOptions.Compiled);
            Regex regexEvent = new Regex(patternEvent, RegexOptions.IgnoreCase | RegexOptions.Compiled);
            Regex regexScriptEnd = new Regex(patternScriptEnd, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            Regex regexScriptBegin = new Regex(patternScriptBegin, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            Regex regexTag = new Regex(patternTag, RegexOptions.Compiled | RegexOptions.IgnoreCase);


            Match matchGeneral, matchEvent, matchScriptEnd, matchScriptBegin, matchTag;

            //符合类似 <abcd> 条件的
            #region 符合类似 <abcd> 条件的
            //过滤字符串中的 </script>   
            for (matchGeneral = regexGeneral.Match(result); matchGeneral.Success; matchGeneral = matchGeneral.NextMatch())
            {
                tmpStr = matchGeneral.Groups[0].Value;
                matchScriptEnd = regexScriptEnd.Match(tmpStr);
                if (matchScriptEnd.Success)
                {
                    tmpStr = regexScriptEnd.Replace(tmpStr, " ");
                    result = result.Replace(matchGeneral.Groups[0].Value, tmpStr);
                }
            }

            //过滤字符串中的脚本事件
            for (matchGeneral = regexGeneral.Match(result); matchGeneral.Success; matchGeneral = matchGeneral.NextMatch())
            {
                tmpStr = matchGeneral.Groups[0].Value;
                matchEvent = regexEvent.Match(tmpStr);
                if (matchEvent.Success)
                {
                    tmpStr = regexEvent.Replace(tmpStr, replaceEventStr);
                    result = result.Replace(matchGeneral.Groups[0].Value, tmpStr);
                }
            }

            //过滤字符串中的 javascript或vbscript:
            for (matchGeneral = regexGeneral.Match(result); matchGeneral.Success; matchGeneral = matchGeneral.NextMatch())
            {
                tmpStr = matchGeneral.Groups[0].Value;
                matchScriptBegin = regexScriptBegin.Match(tmpStr);
                if (matchScriptBegin.Success)
                {
                    tmpStr = regexScriptBegin.Replace(tmpStr, " ");
                    result = result.Replace(matchGeneral.Groups[0].Value, tmpStr);
                }
            }

            #endregion

            //过滤字符串中的事件 例如 onclick --> onXXX
            for (matchEvent = regexEvent.Match(result); matchEvent.Success; matchEvent = matchEvent.NextMatch())
            {
                tmpStr = matchEvent.Groups[0].Value;
                tmpStr = regexEvent.Replace(tmpStr, replaceEventStr);
                result = result.Replace(matchEvent.Groups[0].Value, tmpStr);
            }

            //过滤掉html标签，类似</textarea>
            for (matchTag = regexTag.Match(result); matchTag.Success; matchTag = matchTag.NextMatch())
            {
                tmpStr = matchTag.Groups[0].Value;
                tmpStr = regexTag.Replace(tmpStr, "");
                result = result.Replace(matchTag.Groups[0].Value, tmpStr);
            }


            return result;
        
        }

        /// <summary>
        /// 获取字符串的实际字节长度的方法
        /// </summary>
        /// <param name="s">字符串</param>
        /// <returns>实际长度</returns>
        public static int GetByteLength(this string s)
        {
            return Encoding.Default.GetByteCount(s);
        }

        /// <summary>
        /// 按字节数截取字符串的方法
        /// </summary>
        /// <param name="s">要截取的字符串</param>
        /// <param name="bytes">要截取的字节数</param>
        /// <param name="needEndDot">是否需要结尾的省略号</param>
        /// <returns>截取后的字符串</returns>
        public static string SubStringByBytes(this string s, int bytes, bool needEndDot)
        {
            string temp = string.Empty;
            if (GetByteLength(s) <= bytes)//如果长度比需要的长度n小,返回原字符串
            {
                return s;
            }
            else
            {
                int t = 0;
                char[] q = s.ToCharArray();
                for (int i = 0; i < q.Length && t < bytes; i++)
                {
                    if ((int)q[i] > 127)//是否汉字
                    {
                        temp += q[i];
                        t += 2;
                    }
                    else
                    {
                        temp += q[i];
                        t++;
                    }
                }
                if (needEndDot)
                {
                    temp += "...";
                }
                return temp;
            }
        }


        /// <summary>
        /// 弹出对话框
        /// </summary>
        /// <param name="s">要弹出的内容</param>
        public static void Alert(this string s)
        {
            HttpContext.Current.Response.Write("<script type=\"text/javascript\">alert('"+s+"');</script>");
        }

        /// <summary>
        /// 弹出对话框后，转向指定URL
        /// </summary>
        /// <param name="s">要弹出的内容</param>
        /// <param name="url">要转向的URL</param>
        public static void AlertAndRedirect(this string s, string url)
        {
            HttpContext.Current.Response.Write("<script type=\"text/javascript\">alert('" + s + "');location.href='"+url+"'</script>");
        }
        /// <summary>
        /// 自定义脚本执行
        /// </summary>
        /// <param name="s"></param>
        public static string RunScript(this string s)
        {
            return "<script type=\"text/javascript\">" + s + "</script>";
        }

        /// <summary>
        /// 判断是否为NULL或空值
        /// </summary>
        /// <param name="s">要判断的字串</param>
        /// <returns>为NULL和空值时返回ture，否则为false</returns>
        public static bool IsNullOrEmpty(this string s)
        {
            return string.IsNullOrEmpty(s);
        }

        /// <summary>
        /// 判断是否为数字，正数，小数都可，负数不行
        /// </summary>
        /// <param name="s"></param>
        /// <returns>正确返回True,否则返回False</returns>
        public static bool IsNumeric(this string s)
        {
            return Regex.IsMatch(s, @"^\d+(\.\d+)?$");
        }

        /// <summary>
        /// 判断字符串是否是日期格式
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static bool IsDateTime(this string s)
        {
            return Regex.IsMatch(s, @"^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}(\s{1}\d{1,2}:\d{1,2}:\d{1,2})?$");
        
        }
    }
}
